package pl.edu.agh.sr.lab3.zad2.impl.server;

import org.omg.CORBA.ORB;
import org.omg.CORBA.ORBPackage.InvalidName;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
import org.omg.CosNaming.NamingContextPackage.CannotProceed;
import org.omg.CosNaming.NamingContextPackage.NotFound;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;
import org.omg.PortableServer.POAManagerPackage.AdapterInactive;
import org.omg.PortableServer.POAPackage.ServantNotActive;
import org.omg.PortableServer.POAPackage.WrongPolicy;

import pl.edu.agh.sr.lab3.zad2.impl.common.Config;

public class Server {

	private void initAndStart(String[] args) throws InvalidName,
			AdapterInactive, ServantNotActive, WrongPolicy,
			org.omg.CosNaming.NamingContextPackage.InvalidName, NotFound,
			CannotProceed {
		// create and init ORB
		ORB orb = ORB.init(args, null);

		POA rootpoa = POAHelper.narrow(orb
				.resolve_initial_references("RootPOA"));

		rootpoa.the_POAManager().activate();

		// create servant and get reference
		AFactoryImpl aFactoryImpl = new AFactoryImpl(rootpoa);
		org.omg.CORBA.Object factoryRef = rootpoa
				.servant_to_reference(aFactoryImpl);

		// get NS
		org.omg.CORBA.Object nsRef = orb.string_to_object(Config.getIOR_Reference());
		NamingContextExt ncRef = NamingContextExtHelper.narrow(nsRef);

		// bind servant in NS
		NameComponent path[] = ncRef.to_name(Config.getAFactoryName());
		ncRef.rebind(path, factoryRef);

		// start waiting for client's invocations
		orb.run();
	}

	public static void main(String[] args) {
		Server server = new Server();
		try {
			server.initAndStart(args);
		} catch (Exception e) {
			System.err.println("Server exception: " + e.toString());
		}
	}

}
